package cn.sjx.modules.nbiot.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @Author: ChenBin
 * @Date: 2018/7/16/0016 22:19
 */
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {

    private static final Log logger = LogFactory.get();

    private void showThreadPoolInfo(String prefix) {
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

        if (null == threadPoolExecutor) {
            return;
        }

        logger.debug("================================ 线程池-运行情况 ================================");
        logger.debug("当前执行的操作方式：{}", prefix);
        logger.debug("提交或执行任务个数：{}", threadPoolExecutor.getTaskCount());
        logger.debug("已经完成的任务个数：{}", threadPoolExecutor.getCompletedTaskCount());
        logger.debug("正在处理任务的线程：{}", threadPoolExecutor.getActiveCount());
        logger.debug("队列中等待任务个数：{}", threadPoolExecutor.getQueue().size());
        logger.debug("核心线程/最大线程：{} / {}", this.getCorePoolSize(), this.getMaxPoolSize());
        logger.debug("================================================================================");
    }

    @Override
    public void execute(Runnable task) {
        showThreadPoolInfo("1. do execute");
        super.execute(task);
    }

    @Override
    public void execute(Runnable task, long startTimeout) {
        showThreadPoolInfo("2. do execute");
        super.execute(task, startTimeout);
    }

    @Override
    public Future<?> submit(Runnable task) {
        showThreadPoolInfo("1. do submit");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        showThreadPoolInfo("2. do submit");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        showThreadPoolInfo("1. do submitListenable");
        return super.submitListenable(task);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        showThreadPoolInfo("2. do submitListenable");
        return super.submitListenable(task);
    }
}
